<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>微信支付授权</title>
    <style>
      .loading {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        text-align: center;
      }
      .dialog-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.7);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
      }
      .dialog-content {
        background: white;
        padding: 20px;
        border-radius: 8px;
        width: 80%;
        max-height: 80vh;
        overflow-y: auto;
      }
      .dialog-title {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 15px;
      }
      .dialog-message {
        font-size: 14px;
        line-height: 1.5;
        margin-bottom: 20px;
        text-align: left;
      }
      .dialog-button {
        background: #07c160;
        color: white;
        border: none;
        padding: 8px 20px;
        border-radius: 4px;
        cursor: pointer;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div class="loading">
      <p>正在获取授权...</p>
    </div>

    <script>
      window.BASE_URL =
        "https://nephropathy.zenzer.cn:3286/zyjv3-mp-submit-inspection-api";
    </script>

    <script>
      // getPayUrl: (params) => {
      //   return postRequest('/newpay/pay', { ...params });
      // },

      // notifyPaySuccess: (params) => {
      //       return postRequest('/h5/successPay', { ...params });
      // },

      class WxAuth {
        constructor() {
          this.user = {};
          this.orderNo = this.getUrlParam("orderNo") || "";
          this.orderSource = this.getUrlParam("orderSource") || "";
          this.preOrderId = this.getUrlParam("id") || "";
          this.init();
        }

        // 获取URL参数
        getUrlParam(name) {
          // orderSource、orderNo
          const urlParams = new URLSearchParams(window.location.search);
          return urlParams.get(name);
        }

        // 显示对话框
        showDialog(options) {
          return new Promise((resolve) => {
            const dialog = document.createElement("div");
            dialog.className = "dialog-overlay";
            dialog.innerHTML = `
                        <div class="dialog-content">
                            <div class="dialog-title">${options.title}</div>
                            <div class="dialog-message">${options.message}</div>
                            <button class="dialog-button">确认</button>
                        </div>
                    `;
            document.body.appendChild(dialog);

            dialog.querySelector(".dialog-button").onclick = () => {
              dialog.remove();
              resolve(true);
            };
          });
        }

        // 初始化
        async init() {
          const code = this.getUrlParam("code");
          await this.weChatPageAuthorization(code);
        }

        // 微信网页授权
        async weChatPageAuthorization(code) {
          if (!code) {
            await this.getOauthUrl();
          } else {
            await this.getWxUserInfo(code);
          }
        }

        // 获取微信授权URL
        async getOauthUrl() {
          const redirectUri = encodeURIComponent(
            `${window.location.protocol}//${window.location.host}${window.location.pathname}?id=${this.preOrderId}`
          );

          // 兼容开发环境
          const urlReg =
            /^((http|https):\/\/)(127\.0\.0\.1|localhost|192\.168\.\d{1,3}\.\d{1,3})(:[0-9]+)$/;
          if (
            urlReg.test(`${window.location.protocol}//${window.location.host}`)
          ) {
            console.log("开发环境，使用测试数据");
            this.user = {
              openid: "oMg6O6aT2V6LHdSmGcx_MALYGNk4",
              nickname: "演示",
              headimgurl: "",
            };
            await this.onSubmit();
            return false;
          }

          // 显示授权说明
          await this.showDialog({
            title: "微信网页授权说明",
            message: `尊敬的用户您好，<br><br>
                        为了保护您的个人隐私，我们非常重视您对于获取信息范围和目的的了解。在微信网页授权规范中，我们提供了以下清晰、准确的说明，以帮助您了解我们获取信息的范围和目的。<br><br>
                        <b>获取信息的范围：</b><br>
                        在您授权使用微信网页登录时，我们将仅获取您在微信中公开的基本信息，包括昵称、头像、地区和性别等。我们不会获取您的手机号码、银行账号、密码等敏感信息，也不会访问您微信中的聊天记录和朋友列表等私密信息。<br><br>
                        <b>获取信息的目的：</b><br>
                        我们获取您的基本信息是为了提供更好的服务和个性化体验，具体目的包括但不限于：<br>
                        1. 用于身份认证，确保您的账号安全；<br>
                        2. 显示您的昵称和头像，提升交互体验；<br><br>
                        请注意，我们承诺仅在授权范围内使用您的信息，不会非法获取、泄露或滥用您的个人信息。同时，您有权随时撤销授权并删除您的个人信息。`,
          });

          try {
            // 获取授权URL
            const response = await fetch(
              `${window.BASE_URL}/wxh5/auth2?redirectUri=${redirectUri}&scope=snsapi_userinfo&orderSource=${this.orderSource}`
            );
            const result = await response.json();

            if (result.code === 0 && result.data) {
              window.location.href = result.data;
            } else {
              throw new Error(result.msg || "获取授权URL失败");
            }
          } catch (error) {
            console.error("获取授权URL失败:", error);
            alert("获取授权URL失败: " + error.message);
          }
        }

        // 获取微信用户信息,  3、获取openid
        async getWxUserInfo(code) {
          if (!code) return;

          try {
            const response = await fetch(`${window.BASE_URL}/wxh5/getOpenId`, {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                code: code,
              }),
            });

            const result = await response.json();
            if (result.code === 0 && result.data) {
              this.user = result.data;

              const openId = this.user.openid;

              const response1 = await fetch(`${window.BASE_URL}/newpay/pay`, {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify({
                  orderNo: this.orderNo,
                  openid: this.user.openid,
                  paySource: this.orderSource,
                }),
              });
              const result1 = await response1.json();
              if (response1.ok && response1.jsapiResult.payUrl) {
                var params = {
                  appId: jsapiResult.appId,
                  timeStamp: jsapiResult.timeStamp,
                  nonceStr: jsapiResult.nonceStr,
                  package: jsapiResult.packageData,
                  signType: jsapiResult.signType,
                  paySign: jsapiResult.paySign,
                  success: async function (res) {
                    console.log("调用成功了", res);
                    // Taro.showToast({ title: '支付成功' });
                    // refreshData();
                    // payApi.notifyPaySuccess({ outTradeNo: jsapiResult.out_trade_id, orderNo, openid  });

                    const response2 = await fetch(
                      `${window.BASE_URL}/h5/successPay`,
                      {
                        method: "POST",
                        headers: {
                          "Content-Type": "application/json",
                        },
                        body: JSON.stringify({
                          outTradeNo: jsapiResult.out_trade_id,
                          orderNo: this.orderNo,
                          openid: this.user.openid,
                        }),
                      }
                    );
                  },
                  fail: function (res) {
                    console.log("调用失败了", res);
                    Taro.showToast({ title: "调用失败请重试", icon: "none" });
                  },
                };
              }
              // 已经yo
              // 清理URL中的code
              // const newUrl = `${window.location.protocol}//${window.location.host}${window.location.pathname}?id=${this.preOrderId}`;
              // window.history.replaceState('', '', newUrl);
              // await this.onSubmit();
            } else {
              throw new Error(result.msg || "获取用户信息失败");
            }
          } catch (error) {
            console.error("获取用户信息失败:", error);
            alert("获取用户信息失败: " + error.message);
          }
        }

        // 微信用户登录
        async onSubmit() {
          try {
            const response = await fetch(`${window.BASE_URL}/h5/loginH5`, {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                openid: this.user.openid,
                nickname: this.user.nickname,
                headimgurl: this.user.headimgurl,
                labId: this.getUrlParam("labId") || "",
                phone: "",
              }),
            });

            const result = await response.json();
            if (result.code === 0 && result.data) {
              // 保存token
              // result.data.token && localStorage.setItem('token', result.data.token);
              // this.user.id = result.data.customerId;
              // 这里可以添加登录成功后的处理逻辑
              // window.location.href = `index.html?payParam=${this.preOrderId}&openid=${this.user.openid}`;
            } else {
              throw new Error(result.msg || "登录失败");
            }
          } catch (error) {
            console.error("登录失败:", error);
            alert("登录失败: " + error.message);
          }
        }
      }

      // 页面加载完成后初始化
      document.addEventListener("DOMContentLoaded", () => {
        new WxAuth();
      });
    </script>
  </body>
</html>
